package io.renren.modules.generator.controller;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.renren.modules.generator.entity.MyOssEntity;
import io.renren.modules.generator.service.MyOssService;
import io.renren.modules.generator.utils.fastdfs.FastDFSClient;
import io.renren.modules.generator.utils.fastdfs.FastDFSFile;
import lombok.extern.slf4j.Slf4j;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-11-22 15:05:19
 */
@Slf4j
@RestController
@RequestMapping("generator/myoss")
public class MyOssController {
    @Autowired
    private MyOssService myOssService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:myoss:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = myOssService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:myoss:info")
    public R info(@PathVariable("id") Long id) {
        MyOssEntity myOss = myOssService.getById(id);

        return R.ok().put("myOss", myOss);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:myoss:save")
    public R save(@RequestBody MyOssEntity myOss) {
        myOssService.save(myOss);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:myoss:update")
    public R update(@RequestBody MyOssEntity myOss) {
        myOssService.updateById(myOss);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:myoss:delete")
    public R delete(@RequestBody Long[] ids) {
        myOssService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    // @RequiresPermissions("sys:oss:all")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String path = "";
        String[] fileAbsolutePath = {};
        try {
            fileAbsolutePath = saveFile(file);
            path = FastDFSClient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];// URL
            MyOssEntity myOssEntity = new MyOssEntity();
            myOssEntity.setName(file.getOriginalFilename());
            myOssEntity.setUrl(path);
            myOssEntity.setCreateDate(new Date());
            myOssEntity.setFileSize(file.getSize() + "");
            myOssEntity.setGroupName(fileAbsolutePath[0]);
            myOssEntity.setRemoteFileName(fileAbsolutePath[1]);
            myOssService.save(myOssEntity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 上传文件
        // String suffix =
        // file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

        // // 保存文件信息
        // SysOssEntity ossEntity = new SysOssEntity();
        // ossEntity.setUrl(url);
        // ossEntity.setCreateDate(new Date());
        // sysOssService.save(ossEntity);

        return R.ok().put("url", path);
    }

    /**
     * 从MultipartFile读取文件信息，然后使用FastDFSClient将文件上传到FastDFS集群中，并返回上传文件后的地址信息
     * 
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String[] saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath = {};
        String fileName = multipartFile.getOriginalFilename();
        log.info("fileName = " + fileName);
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream = multipartFile.getInputStream();
        if (inputStream != null) {
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file); // upload to fastdfs
        } catch (Exception e) {
            log.error("upload file Exception!", e);
        }
        if (fileAbsolutePath == null) {
            log.error("upload file failed,please upload again!");
        }
        // String path = FastDFSClient.getTrackerUrl() + fileAbsolutePath[0] + "/" +
        // fileAbsolutePath[1];
        for (String str : fileAbsolutePath) {
            log.info("......................." + str);
        }
        // return path;
        return fileAbsolutePath;
    }
}
